package org.jeecg.modules.wmhb.job;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 订货明细自动更新到货时间和采购时间（只更新没有序号的订货明细数据）
 */
@Slf4j
public class PurchaseTaskbookProgressJob implements Job {
    @Autowired
    private IWmPurchaseOrderDetailService purchaseOrderDetailService;
    @Autowired
    private IWmPurchaseOrderDetailDyService purchaseOrderDetailDyService;
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmTaskBomService wmTaskBomService;
    @Autowired
    private IWmTaskLogService wmTaskLogService;
    @Autowired
    private IWmTaskbookService wmTaskbookService;
    @Autowired
    private IWmPurchaseTaskbookBomService wmPurchaseTaskbookBomService;
    @Autowired
    private IWmFlowDeptService wmFlowDeptService;
    @Autowired
    private IWmTaskFlowService wmTaskFlowService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format(" =============PurchaseTaskbookProgressJob============ !  时间:" + DateUtils.getTimestamp()));
        //获取所有未到货的采购任务书BOM
        List<WmPurchaseTaskbookBom> wmPurchaseTaskbookBomList = wmPurchaseTaskbookBomService.queryNotArriveBom();

        //获取没有序号的订货明细数据（采购任务书没有序号和物资申请编号）
        List<WmPurchaseOrderDetail> wmPurchaseOrderDetailList = purchaseOrderDetailService.queryNoSeriesNoOfPurchaseBom();

        //获取没有物资申请编号的电仪订货明细数据
        List<WmPurchaseOrderDetailDy> wmPurchaseOrderDetailDyList = purchaseOrderDetailDyService.queryNoSeriesNoOfPurchaseBom();

        //更新采购时间和到货时间到货数量
        for(WmPurchaseTaskbookBom wmPurchaseTaskbookBom: wmPurchaseTaskbookBomList) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmPurchaseTaskbookBom.getWmTaskbookId());
            WmTask wmTask = wmTaskService.getById(wmPurchaseTaskbookBom.getWmTaskId());

            if(wmTask == null || wmTaskbook == null){
                continue;
            }

            wmPurchaseTaskbookBom.setName(wmTask.getName());//根任务名称为合同产品名称
            for (WmPurchaseOrderDetail wmPurchaseOrderDetail : wmPurchaseOrderDetailList) {
                isAllPurchaseOrArrive(wmPurchaseOrderDetail, wmPurchaseTaskbookBom, wmTaskbook);
            }

            for (WmPurchaseOrderDetailDy wmPurchaseOrderDetailDy : wmPurchaseOrderDetailDyList) {
                isAllPurchaseOrArrive(wmPurchaseOrderDetailDy, wmPurchaseTaskbookBom, wmTaskbook);
            }
        }
    }

    /**
     * 任务下一流程
     * @param wmTask
     * @return
     */
    private void nextFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、下一流程
        Integer nextIndex = wmTask.getCurrentNodeIndex() + 1;
        if(nextIndex >= wmFlowDeptList.size()){
            //throw new RuntimeException("请补充完整的流程定义");
            return;
        }
        wmTask.setCurrentNodeIndex(nextIndex);
        wmTask.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
        wmTask.setCurrentNodeTime(new Date());
        wmTaskService.updateById(wmTask);

        //3、设置上一流程实际结束时间和当前流程实际开始时间
        WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex-1);
        WmTaskFlow wmTaskFlowNext = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex);
        wmTaskFlowCurr.setFactEndTime(new Date());
        wmTaskFlowNext.setFactBeginTime(new Date());
        wmTaskFlowService.updateById(wmTaskFlowCurr);
        wmTaskFlowService.updateById(wmTaskFlowNext);

        //4、更新任务书当前流程部门
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setCurrentNodeIndex(nextIndex);
            wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

    /**
     * 检测同一任务下的采购BOM是否都已采购或都已到货
     * @param wmPurchaseOrderDetail
     * @param wmPurchaseTaskbookBom
     * @param wmTaskbook
     */
    private void isAllPurchaseOrArrive(WmPurchaseOrderDetail wmPurchaseOrderDetail, WmPurchaseTaskbookBom wmPurchaseTaskbookBom, WmTaskbook wmTaskbook){
        //订货明细备注里是否包含任务号
        if (wmTaskbook != null && !StringUtils.isEmpty(wmPurchaseOrderDetail.getRemark()) && wmPurchaseOrderDetail.getRemark().contains(wmTaskbook.getCode()) && wmPurchaseTaskbookBom.getName().equals(wmPurchaseOrderDetail.getJdName())) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //如果采购任务BOM没有记录采购时间，而订货明细有订货时间，则更新任务BOM的采购时间
            if (wmPurchaseTaskbookBom.getPurchaseTime() == null && !StringUtils.isEmpty(wmPurchaseOrderDetail.getOrderDate())) {
                try {
                    Date purchaseTime = format.parse(wmPurchaseOrderDetail.getOrderDate());
                    wmPurchaseTaskbookBom.setPurchaseTime(purchaseTime);
                    wmPurchaseTaskbookBom.setStatus(UserConstant.PURCHASE_TASKBOOK_STATUS_PURCHASED);
                    wmPurchaseTaskbookBomService.updateById(wmPurchaseTaskbookBom);

                    //判断同任务下所有采购BOM是否都采购了
                    Boolean allPurchase = true;
                    List<WmPurchaseTaskbookBom> purchaseTaskbookBomList = wmPurchaseTaskbookBomService.listByWmTaskId(wmPurchaseTaskbookBom.getWmTaskId());
                    for(WmPurchaseTaskbookBom purchaseTaskbookBom: purchaseTaskbookBomList){
                        if(!purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_PURCHASED) && !purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_ARRIVED)  && !purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_FINISHED)){
                            allPurchase = false;
                            break;
                        }
                    }

                    //更新任务为采购状态
                    if(allPurchase){
                        WmTask wmTask = wmTaskService.getById(wmPurchaseTaskbookBom.getWmTaskId());
                        wmTask.setStatus(UserConstant.TASK_STATUS_PURCHASED);
                        wmTask.setProgress("70");//已采购算70%
                        nextFlowTask(wmTask);
                    }
                }
                catch (ParseException e) {}
            }

            //如果任务BOM没有记录到货时间，而订货明细有订货时间，则更新任务BOM的到货时间
            if (wmPurchaseTaskbookBom.getArriveTime() == null && !StringUtils.isEmpty(wmPurchaseOrderDetail.getFactArriveTime()) && !StringUtils.isEmpty(wmPurchaseOrderDetail.getQuantity())) {
                try {
                    Date arriveTime = format.parse(wmPurchaseOrderDetail.getFactArriveTime());
                    wmPurchaseTaskbookBom.setArriveTime(arriveTime);
                    wmPurchaseTaskbookBom.setStatus(UserConstant.PURCHASE_TASKBOOK_STATUS_ARRIVED);
                    wmPurchaseTaskbookBom.setQuantity(Double.parseDouble(wmPurchaseOrderDetail.getQuantity()));
                    wmPurchaseTaskbookBomService.updateById(wmPurchaseTaskbookBom);

                    wmPurchaseOrderDetail.setIsCheckPurchaseBom(UserConstant.SYS_YES);
                    purchaseOrderDetailService.updateById(wmPurchaseOrderDetail);

                    //判断同任务下所有采购BOM是否都到货了
                    Boolean allArrive = true;
                    List<WmPurchaseTaskbookBom> purchaseTaskbookBomList = wmPurchaseTaskbookBomService.listByWmTaskId(wmPurchaseTaskbookBom.getWmTaskId());
                    for(WmPurchaseTaskbookBom purchaseTaskbookBom: purchaseTaskbookBomList){
                        if(!purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_ARRIVED) && !purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_FINISHED)){
                            allArrive = false;
                            break;
                        }
                    }

                    //更新任务为到货状态
                    if(allArrive){
                        WmTask wmTask = wmTaskService.getById(wmPurchaseTaskbookBom.getWmTaskId());
                        wmTask.setStatus(UserConstant.TASK_STATUS_ARRIVED);
                        wmTask.setProgress("90");//已到货算90%
                        nextFlowTask(wmTask);
                    }
                }
                catch (ParseException e) {}
            }
        }
    }

    /**
     * 检测同一任务下的采购BOM是否都已采购或都已到货
     * @param wmPurchaseOrderDetailDy
     * @param wmPurchaseTaskbookBom
     * @param wmTaskbook
     */
    private void isAllPurchaseOrArrive(WmPurchaseOrderDetailDy wmPurchaseOrderDetailDy, WmPurchaseTaskbookBom wmPurchaseTaskbookBom, WmTaskbook wmTaskbook){
        //订货明细备注里是否包含任务号
        if (wmTaskbook != null && !StringUtils.isEmpty(wmPurchaseOrderDetailDy.getTaskNo()) && wmPurchaseOrderDetailDy.getTaskNo().equals(wmTaskbook.getCode()) && wmPurchaseTaskbookBom.getName().equals(wmPurchaseOrderDetailDy.getJdName())) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            //如果采购任务BOM没有记录采购时间，而订货明细有订货时间，则更新任务BOM的采购时间
            if (wmPurchaseTaskbookBom.getPurchaseTime() == null && !StringUtils.isEmpty(wmPurchaseOrderDetailDy.getOrderDate())) {
                try {
                    Date purchaseTime = format.parse(wmPurchaseOrderDetailDy.getOrderDate());
                    wmPurchaseTaskbookBom.setPurchaseTime(purchaseTime);
                    wmPurchaseTaskbookBom.setStatus(UserConstant.PURCHASE_TASKBOOK_STATUS_PURCHASED);
                    wmPurchaseTaskbookBomService.updateById(wmPurchaseTaskbookBom);

                    //判断同任务下所有采购BOM是否都采购了
                    Boolean allPurchase = true;
                    List<WmPurchaseTaskbookBom> purchaseTaskbookBomList = wmPurchaseTaskbookBomService.listByWmTaskId(wmPurchaseTaskbookBom.getWmTaskId());
                    for(WmPurchaseTaskbookBom purchaseTaskbookBom: purchaseTaskbookBomList){
                        if(!purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_PURCHASED) && !purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_ARRIVED)  && !purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_FINISHED)){
                            allPurchase = false;
                            break;
                        }
                    }

                    //更新任务为采购状态
                    if(allPurchase){
                        WmTask wmTask = wmTaskService.getById(wmPurchaseTaskbookBom.getWmTaskId());
                        wmTask.setStatus(UserConstant.TASK_STATUS_PURCHASED);
                        wmTask.setProgress("70");//已采购算70%
                        nextFlowTask(wmTask);
                    }
                }
                catch (ParseException e) {}
            }

            //如果任务BOM没有记录到货时间，而订货明细有订货时间，则更新任务BOM的到货时间
            if (wmPurchaseTaskbookBom.getArriveTime() == null && !StringUtils.isEmpty(wmPurchaseOrderDetailDy.getFactArriveTime()) && !StringUtils.isEmpty(wmPurchaseOrderDetailDy.getQuantity())) {
                try {
                    Date arriveTime = format.parse(wmPurchaseOrderDetailDy.getFactArriveTime());
                    wmPurchaseTaskbookBom.setArriveTime(arriveTime);
                    wmPurchaseTaskbookBom.setStatus(UserConstant.PURCHASE_TASKBOOK_STATUS_ARRIVED);
                    wmPurchaseTaskbookBom.setQuantity(Double.parseDouble(wmPurchaseOrderDetailDy.getQuantity()));
                    wmPurchaseTaskbookBomService.updateById(wmPurchaseTaskbookBom);

                    //判断同任务下所有采购BOM是否都到货了
                    Boolean allArrive = true;
                    List<WmPurchaseTaskbookBom> purchaseTaskbookBomList = wmPurchaseTaskbookBomService.listByWmTaskId(wmPurchaseTaskbookBom.getWmTaskId());
                    for(WmPurchaseTaskbookBom purchaseTaskbookBom: purchaseTaskbookBomList){
                        if(!purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_ARRIVED) && !purchaseTaskbookBom.getStatus().equals(UserConstant.PURCHASE_TASKBOOK_STATUS_FINISHED)){
                            allArrive = false;
                            break;
                        }
                    }

                    //更新任务为到货状态
                    if(allArrive){
                        WmTask wmTask = wmTaskService.getById(wmPurchaseTaskbookBom.getWmTaskId());
                        wmTask.setStatus(UserConstant.TASK_STATUS_ARRIVED);
                        wmTask.setProgress("90");//已到货算90%
                        nextFlowTask(wmTask);
                    }
                }
                catch (ParseException e) {}
            }
        }
    }
}
